IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[HIS.WZ.002_details]')AND type IN (N'P', N'PC'))
	DROP PROCEDURE [dbo].[HIS.WZ.002_details];
GO

SET ANSI_NULLS ON;
GO

SET QUOTED_IDENTIFIER ON;
GO
CREATE PROCEDURE [dbo].[HIS.WZ.002_details](@limitTime VARCHAR(10),@kdks VARCHAR(20))
AS

DECLARE @kssj DATETIME,@jssj DATETIME

SET @kdks='%'+@kdks+'%'

IF (LEN(RTRIM(@limitTime))=4) 
BEGIN
    SELECT @kssj=CONVERT(DATETIME,@limitTime+'0101')
	SELECT @jssj=DATEADD(YEAR,1,@kssj)
END
ELSE
BEGIN
    SELECT @kssj=CONVERT(DATETIME,@limitTime+'01')
	SELECT @jssj=DATEADD(MONTH,1,@kssj)
END 

CREATE TABLE #temp1(
cfbh VARCHAR(20),
hjrq DATETIME,
ksdm VARCHAR(4),
ksmc VARCHAR(50)
)

INSERT INTO #temp1(ksdm,ksmc,cfbh, hjrq)
SELECT kdksdm,kdksmc,cfbh,hjrq FROM dbo.his_wz_cffymx 
WHERE hjrq>=@kssj AND hjrq<@jssj 
AND ypsl>0 



SELECT  ksdm, ksmc,COUNT(DISTINCT cfbh) sj,@limitTime tjsj FROM #temp1
WHERE  ksmc LIKE @kdks
GROUP BY ksdm,ksmc

GO


/*
EXEC dbo.[HIS.WZ.002] @startdate = '2018-02-01 07:43:15', -- datetime
      @enddate = '2019-08-27 07:43:15', -- datetime
    @type = 'month' -- varchar(10)


EXEC dbo.[HIS.WZ.002_details] @limitTime = '2019', -- datetime
    @brkh = '', -- datetime
    @ghks = '' -- varchar(10)

EXEC dbo.[HIS.WZ.002_details] '201905',''
*/
